#include "CDynamicArray.h"
#include <string.h>
#include <stdlib.h>

CDynamicArray::CDynamicArray(int nInitialMaxSize)
{
	m_nSize = 0;
	m_nFreeSize = nInitialMaxSize;
	m_cArray = new char[m_nFreeSize];
}

CDynamicArray::CDynamicArray(CDynamicArray* cDynamicArray)
{
	if (cDynamicArray != NULL)
	{
		m_nSize = cDynamicArray->m_nSize;
		m_nFreeSize = m_nSize;
		m_cArray = new char[m_nSize];
		memcpy(m_cArray, cDynamicArray->m_cArray, m_nSize);
	}
	else
	{
		m_nSize = 0;
		m_nFreeSize = INITIAL_MAX_SIZE;
		m_cArray = new char[INITIAL_MAX_SIZE];
	}
}

CDynamicArray::~CDynamicArray(void)
{
	delete [] m_cArray;
}

void CDynamicArray::copyToArray(const char* source, unsigned int size){
	// allocates a new array array of size: m_nSize+5*size 
	_resize(size);
    // copies the data pointed by source to the newly allocated array 
	memcpy(m_cArray + m_nSize, source, size);
	// updating the array's current size
	m_nSize += size; 
    // updating the array's free space 
	m_nFreeSize-=size; 
}

void CDynamicArray::_resize(int nNewSize){
	if (m_nFreeSize >= nNewSize){
		return;
	}

	int nNewArraySize = m_nSize + 5*nNewSize;

	char* cNewarr = new char[nNewArraySize];
    // copies the data that is now stored in the data array
   //    to the newly allocated (resized) array 
	memcpy(cNewarr, m_cArray, m_nSize);
									   
    // deleting the previous array 
	delete [] m_cArray; 
    // changes the class pointer m_cArray to point to the resized array 
	m_cArray = cNewarr; 
	m_nFreeSize = nNewArraySize - m_nSize;
}
